package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.MajorManager;
import com.xyzh05.model.Major;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class MajorAction extends BaseAction implements Preparable {
    private MajorManager majorManager;
    private List majors;
    private Major major;
    private Long id;
    private String query;

    public void setMajorManager(MajorManager majorManager) {
        this.majorManager = majorManager;
    }

    public List getMajors() {
        return majors;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String majorId = getRequest().getParameter("major.id");
            if (majorId != null && !majorId.equals("")) {
                major = majorManager.get(new Long(majorId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        majors = majorManager.search(query, Major.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Major getMajor() {
        return major;
    }

    public void setMajor(Major major) {
        this.major = major;
    }

    public String delete() {
        majorManager.remove(major.getId());
        saveMessage(getText("major.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            major = majorManager.get(id);
        } else {
            major = new Major();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (major.getId() == null);

        majorManager.save(major);

        String key = (isNew) ? "major.added" : "major.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}